package com.foreknow.springboot.service.impl;

import com.foreknow.springboot.mapper.CartMapper;
import com.foreknow.springboot.mapper.OrderdetailetMapper;
import com.foreknow.springboot.mapper.OrdersMapper;
import com.foreknow.springboot.po.*;
import com.foreknow.springboot.service.OrdersService;
import com.foreknow.springboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"all"})
/**
 * @author xiaoming
 * @version jdk1.8
 * @date 2022/8/13 22:30
 * @function:
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderdetailetMapper orderdetailetMapper;

    @Override
    public int saveOrder(String userId, Integer businessId, Integer daId, String orderTotal){
        int orderId = 0;
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(businessId);
        List<Cart> list = cartMapper.listCart(cart);

        Orders orders = new Orders();
        String date = CommonUtil.getCurrentDate();
        orders.setUserId(userId);
        orders.setBusinessId(businessId);
        orders.setOrderDate(date);
        orders.setOrderTotal(orderTotal);
        orders.setDaId(daId);
        orders.setOrderState(0);
        ordersMapper.saveOrder(orders);
        orderId = orders.getOrderId();

        List<Orderdetailet> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Cart cart1 = list.get(i);
            Integer foodId = cart1.getFoodId();
            Integer quantity = cart1.getQuantity();
            Orderdetailet orderdetailet = new Orderdetailet();
            orderdetailet.setFoodId(foodId);
            orderdetailet.setQuantity(quantity);
            orderdetailet.setOrderId(orderId);
            list1.add(orderdetailet);
        }
        orderdetailetMapper.save(list1);
        cartMapper.removeCart(cart);

        return orderId;
    }
    @Override
    public Orders getOrdersById(Integer orderId) {

        return ordersMapper.getOrdersById(orderId);

    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        ArrayList<Orders> list2 = new ArrayList<>();
        List<Orders> list = ordersMapper.listOrdersByUserId(userId);
        for (int i = 0;i<list.size();i++) {
            Orders orders = list.get(i);
            List<Orderdetailet> list1 = orderdetailetMapper.save2(orders);
            orders.setList(list1);
            list2.add(orders);
        }
        return list2;
    }
}
